package com.acs.player.media;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import android.app.Activity;
import android.content.ContentUris;
import android.database.Cursor;
import android.provider.MediaStore;

import com.acs.player.entities.Album;
import com.acs.player.entities.Artiste;
import com.acs.player.entities.Music;

public class RetrieveData {

	private final static String[] EXTENSIONS = { ".mp3", ".mid", ".wav", ".ogg", ".mp4" }; //Playable Extensions
	
	private static String coverUnknown = "Unknown";
	private static List<Music> allTracksList = new ArrayList<Music>();
	private static List<Album> albumsList = new ArrayList<Album>();
	private static RetrieveData instance;
	
	private RetrieveData(){		
	};
	
	public static RetrieveData getRetrieveData(Activity activity){
		if(instance == null){
			instance = new RetrieveData();
			initTracks(activity);
			initAlbums();
		}
		return instance;
	}
	
	private static void initTracks(Activity activity){

		allTracksList = new ArrayList<Music>();
		
        String[] projection = new String[] {
        		MediaStore.Audio.Media.ARTIST, 
        		MediaStore.Audio.Media.TITLE,
        		MediaStore.Audio.Media.DATA,
        		MediaStore.Audio.Media.ALBUM_ID,
        		MediaStore.Audio.Media.DURATION
        };
        
        Cursor mCur = activity.managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, null, null, null);
        mCur.moveToFirst();
 
        while (mCur.isAfterLast() == false) {

        	int artistIndex = mCur.getColumnIndex(MediaStore.Audio.Media.ARTIST);
        	int titreIndex = mCur.getColumnIndex(MediaStore.Audio.Media.TITLE);
        	int dataIndex = mCur.getColumnIndex(MediaStore.Audio.Media.DATA);
        	int albumIdIndex = mCur.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID);
        	int durationIndex = mCur.getColumnIndex(MediaStore.Audio.Media.DURATION);
        	
        	String artisteName =  mCur.getString(artistIndex);
       	    String titre = mCur.getString(titreIndex);
       	    String path = mCur.getString(dataIndex);
       	    int albumId = mCur.getInt(albumIdIndex);
       	    long duration = mCur.getLong(durationIndex);
       	    
       	    boolean isValideTrack = trackChecker(path);
       	    
       	    if(isValideTrack){        
       	    	
				Cursor cursor = activity.getContentResolver().query(
			              ContentUris.withAppendedId(
			                  MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, albumId),
			              new String[] { MediaStore.Audio.AlbumColumns.ALBUM , MediaStore.Audio.AlbumColumns.ALBUM_ART },
			              null,
			              null,
			              null);
				
				String albumName = null;
				String albumArtPath = null;
			
				if (cursor.moveToFirst()) {
					albumName = cursor.getString(0);			
				    albumArtPath = cursor.getString(1);
				}
				    
		       	cursor.close();
		       	
		       	Artiste artiste = new Artiste(artisteName);
		       	Album album = new Album(albumName, albumArtPath);
	
		       	Music music = new Music();
		       	music.setArtiste(artiste);
		       	music.setTitre(titre);
		       	music.setDuration(duration);
		       	music.setAlbulm(album);
		       	music.setPath(path);
		       	
		       	allTracksList.add(music);
	
	            mCur.moveToNext();     
       	    }
        }
        
	}
	
	private static void initAlbums(){	
		Map<String, Album> albumsMap = new HashMap<String, Album>();
		
		for (Music music : allTracksList) {
			Album currentAlbum = music.getAlbulm();
			String albumName = currentAlbum.getNom();
				
			if(albumsMap.containsKey(albumName)){
				Album album = albumsMap.get(albumName);
				album.getTrackList().add(music);
			} else {
				currentAlbum.getTrackList().add(music);
				albumsMap.put(albumName, currentAlbum);
			}
		}
		
		for (Entry<String, Album> entry : albumsMap.entrySet()) {
		    Album album = entry.getValue();
		    albumsList.add(album);
		}	
	}
	
    /**
     * Checks to make sure that the track to be loaded has a correct extenson.
     * @param trackToTest
     * @return
     */
    private static boolean trackChecker(String trackToTest){
    	for(int j = 0; j < EXTENSIONS.length; j++){
			if(trackToTest.contains(EXTENSIONS[j])){
				return true;
			}
		}
    	return false;
    }

	public List<Music> getAllTracksList() {
		return allTracksList;
	}
	
	public List<Music> getTrackByTitleID(int id){
		List<Music> resultList = new ArrayList<Music>();
		Music music = allTracksList.get(id);
		resultList.add(music);
		return resultList;
	}

	public List<Album> getAlbumsList() {
		return albumsList;
	}
}
